package com.gilgamesh.mall.product.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.gilgamesh.mall.product.dao.ClassficDao;
import com.gilgamesh.mall.product.dao.ImageDao;
import com.gilgamesh.mall.product.dao.ProductDao;
import com.gilgamesh.mall.product.dao.ProductDetailDao;
import com.gilgamesh.mall.product.service.ProductService;
import com.gilgamesh.mall.sdk.bean.product.ClassficEntity;
import com.gilgamesh.mall.sdk.bean.product.ImageEntity;
import com.gilgamesh.mall.sdk.bean.product.ProductDetailEntity;
import com.gilgamesh.mall.sdk.bean.product.ProductEntity;
import com.gilgamesh.mall.sdk.common.RedisConstant;
import com.gilgamesh.mall.sdk.dto.ResponseDTO;
import com.gilgamesh.mall.sdk.dto.product.*;
import com.gilgamesh.mall.sdk.util.BeanUtil;
import com.gilgamesh.mall.sdk.util.CollectionUtil;
import com.gilgamesh.mall.sdk.util.CommonException;
import com.gilgamesh.mall.sdk.util.ResponseUtil;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import java.util.*;

/**
 * 商品服务impl
 *
 * @author yanm
 * @date 2021/1/13 9:45
 **/
@Service
@Slf4j
@RequiredArgsConstructor(onConstructor = @__(@Autowired))
public class ProductServiceImpl implements ProductService {

    private final ProductDao productDao;

    private final ProductDetailDao productDetailDao;

    private final RedisTemplate redisTemplate;

    private final ClassficDao classficDao;

    private final ImageDao imageDao;


    @Override
    public String getProductCode() {
        Random random = new Random();
        StringBuilder sb = new StringBuilder();
        boolean flag = false;
        while (!flag) {
            while (sb.length() < RedisConstant.PRODUCT_CODE_LNGTH) {
                int get = random.nextInt(999999);
                while (get < 100000) {
                    get = random.nextInt(999999);
                }
                sb.append(get);
            }
            if (redisTemplate.opsForValue().get(RedisConstant.PRODUCT_CODE + ":" + sb.toString()) == null) {
                flag = true;
                redisTemplate.opsForValue().set(RedisConstant.PRODUCT_CODE + ":" + sb.toString(), sb.toString());
            } else {
                sb = new StringBuilder();
            }
        }
        return sb.toString();
    }


    @Override
    public String getSkuCode() {
        Random random = new Random();
        StringBuilder sb = new StringBuilder();
        boolean flag = false;
        while (!flag) {
            while (sb.length() < RedisConstant.SKU_CODE_LENGTH) {
                int get = random.nextInt(999999);
                while (get < 100000) {
                    get = random.nextInt(999999);
                }
                sb.append(get);
            }
            if (redisTemplate.opsForValue().get(RedisConstant.SKU_CODE + ":" + sb.toString()) == null) {
                flag = true;
                redisTemplate.opsForValue().set(RedisConstant.SKU_CODE + ":" + sb.toString(), sb.toString());
            } else {
                sb = new StringBuilder();
            }
        }
        return sb.toString();
    }

    @Override
    public ResponseDTO<Integer> createProduct(ProductEntity productEntity) {
        if (log.isDebugEnabled()) {
            log.debug("productEntity is,{}", productEntity);
        }
        if (BeanUtil.isLogicalNull(productEntity)) {
            throw new CommonException("productEntity不能为空");
        }
        productEntity.setProductCode(getProductCode());
        return ResponseUtil.getResponse(productDao.insert(productEntity));
    }


    @Override
    public ResponseDTO<ImageDTO> getImageName() {
        Random random = new Random();
        StringBuilder sb = new StringBuilder();
        boolean flag = false;
        while (!flag) {
            while (sb.length() < RedisConstant.SKU_CODE_LENGTH) {
                int get = random.nextInt(999999);
                while (get < 100000) {
                    get = random.nextInt(999999);
                }
                sb.append(get);
            }
            if (redisTemplate.opsForValue().get(RedisConstant.PRODUCT_IMAGE_URL+ ":" + sb.toString()) == null) {
                flag = true;
                redisTemplate.opsForValue().set(RedisConstant.PRODUCT_IMAGE_URL + ":" + sb.toString(), sb.toString());
            } else {
                sb = new StringBuilder();
            }
        }
        ImageEntity imageEntity = new ImageEntity();
        imageEntity.setImageUri(sb.toString());
        ImageDTO imageDTO = new ImageDTO();
        BeanUtils.copyProperties(imageEntity,imageDTO);
        return ResponseUtil.getResponse(imageDTO);
    }

    @Override
    public ResponseDTO<ProductDTO> getProductById(Long id) {
        ResponseDTO<ProductDTO> responseDTO = new ResponseDTO<>();
        ProductDTO productDTO = productDao.getById(id);
        responseDTO.setData(productDTO);
        if(BeanUtil.isLogicalNull(responseDTO)){
            responseDTO.setCode("0");
            responseDTO.setMessage("success");
            responseDTO.setSuccess(Boolean.TRUE);
        }
        return responseDTO;
    }

    @Override
    public ResponseDTO<List<ProductDTO>> listProduct(ProductEntity productEntity) {
        if (log.isDebugEnabled()) {
            log.debug("productEntity is,{}", productEntity);
        }
        ResponseDTO<List<ProductDTO>> responseDTO = new ResponseDTO<>();
        responseDTO.setData(productDao.listProducts(productEntity));
        if (CollectionUtil.isNotEmpty(responseDTO.getData())) {
            responseDTO.setCode("0");
            responseDTO.setMessage("success");
            responseDTO.setSuccess(Boolean.TRUE);
        }
        return responseDTO;
    }

    @Override
    public List<ProductDTO> listProductV2() {
        Random random = new Random();
        int count = productDao.selectCount(null);
        Set<Integer> set = new HashSet<>();
        while(set.size()<36){
            set.add(random.nextInt(count));
        }
        List<ProductDTO> all = productDao.listProducts(null);
        List<ProductDTO> ret = new ArrayList<>();
        for (Integer i : set) {
            ret.add(all.get(i));
        }
        return ret;
    }


    @Override
    public List<ProductDTO> guessYouLikeV2() {
        Random random = new Random();
        int count = productDao.selectCount(null);
        Set<Integer> set = new HashSet<>();
        while(set.size()<6){
            set.add(random.nextInt(count));
        }
        List<ProductDTO> all = productDao.listProducts(null);
        List<ProductDTO> ret = new ArrayList<>();
        for (Integer i : set) {
            ret.add(all.get(i));
        }
        return ret;
    }
    @Override
    public List<ProductDTO> searchProductV2(String keyWord) {
        List<ClassficDTO> classficDTOS = classficDao.listByKeyWord(keyWord);
        int count = classficDTOS.size();
        System.out.println("-----关键词检索到的类别数量 = "+count);
        if(CollectionUtil.isNotEmpty(classficDTOS)){
            Random r = new Random();
            ClassficDTO ct = classficDTOS.get(r.nextInt(count));
            ProductEntity pe = new ProductEntity();
            pe.setClassfic3Id(ct.getId());
            List<ProductDTO> all = productDao.listProducts(pe);
            int count2 = all.size();
            System.out.println("-----关键词对应的商品数量 ="+all.size());
            if(count2<36){
                List<ProductDTO> productDTOS = listProductV2();
                for (ProductDTO productDTO : productDTOS) {
                    all.add(productDTO);
                }
                count2 += productDTOS.size();
                System.out.println("*-----补充了额外随机商品条数 = "+count2);
            }

            Set<Integer> set = new HashSet<>();
            while(set.size()<36){
                set.add(r.nextInt(count2));
            }
            List<ProductDTO> ret = new ArrayList<>();
            for (Integer i : set) {
                ret.add(all.get(i));
            }
            System.out.println("-----随机检索到的商品数量 = "+ret.size());
            return ret;
        }
        return null;
    }


    @Override
    public Shop2DetailDTO detailPageV2(String productCode) {
        Shop2DetailDTO s2dd = new Shop2DetailDTO();
        ProductEntity entity = new ProductEntity();
        entity.setProductCode(productCode);
        entity = productDao.selectList(new QueryWrapper<>(entity)).get(0);
        s2dd.setPe(entity);
        ProductDetailEntity pde = new ProductDetailEntity();
        pde.setProductCode(productCode);
        List<ProductDetailDTO> pdes = productDetailDao.listProductDetails(pde);
        for (ProductDetailDTO pddo : pdes) {
            ImageEntity ie = new ImageEntity();
            ie.setSkuCode(pddo.getSkuCode());
            List<ImageDTO> ido = imageDao.listImages(ie);

            Set<ImageDTO> set = new HashSet<>();
            set.addAll(ido);
            List<ImageDTO> imageDTOS = new ArrayList<>();
            for (ImageDTO imageDTO : set) {
                imageDTOS.add(imageDTO);
            }
            pddo.setIs(imageDTOS);
        }
        s2dd.setPdes(pdes);
        ClassficEntity c3 = new ClassficEntity();
        c3.setId(entity.getClassfic3Id());
        c3 = classficDao.listClassfics(c3).get(0);
        s2dd.setC3(c3);

        ClassficEntity c2 = new ClassficEntity();
        c2.setId(entity.getClassfic2Id());
        c2 = classficDao.listClassfics(c2).get(0);
        s2dd.setC2(c2);

        ClassficEntity c = new ClassficEntity();
        c.setId(entity.getClassficId());
        c = classficDao.listClassfics(c).get(0);
        s2dd.setC(c);

        return s2dd;
    }
}
